package com.etc.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.etc.entity.User;
import com.etc.service.UserService;
import com.etc.utils.EnDecryptUtil;
import com.etc.utils.FTPUtil;

/**
 * 实现用户登录验证和注册的相关功能
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	
	@RequestMapping("userinfo")
	public String showUserInfo(){
		
		return "userinfo";
	}
	
	@RequestMapping("updatePwd")
	@ResponseBody
	public String updatePwd(@RequestParam("oldpwd")String oldpwd,@RequestParam("newpwd")String newpwd,HttpSession session,HttpServletResponse response){
		User user = (User) session.getAttribute("user");
		User user2 = userService.checkUser(user.getUno(), EnDecryptUtil.SHA1(oldpwd));
		if (user2==null) {
			return "oldpwderr";
		}
		
		newpwd=EnDecryptUtil.SHA1(newpwd);
		user.setUpwd(newpwd);
		int i = userService.updateUserInfoByUid(user);
		if (i>0) {
			session.removeAttribute("user");
			Cookie upwd = new Cookie("upwd", null);
			upwd.setMaxAge(0);
			response.addCookie(upwd);
			return "success";
		}
		return "404";
	}
	
	
	@RequestMapping("editUimg")
	@ResponseBody
	public String editUimg(@RequestParam("file") MultipartFile multipartFile,HttpSession session){
		User user = (User) session.getAttribute("user");
		
		Random r = new Random();
		List<File> fileList = new ArrayList<File>();
		//对文件名重命名，加个随机数
		String fileName = multipartFile.getOriginalFilename();
		String[] split = fileName.split(".jpg");
		fileName = split[0] + r.nextInt(1000);
		fileName = fileName + ".jpg";
		
		
		File dest = new File("D:/upload/"+fileName);
		try {
			multipartFile.transferTo(dest);
			fileList.add(dest);
			boolean b = FTPUtil.uploadFile(fileList);
			if (b) {
				user.setUimg("http://image.amall.com/img/"+fileName);
				int i = userService.updateUserInfoByUid(user);
				if (i>0) {
					session.setAttribute("user", user);
					return "success";
				}
			}else{
				return null;
			}
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping("logout")
	public String logout(HttpSession session,HttpServletResponse response) throws IOException{
		User user = (User) session.getAttribute("user");
		if (user!=null) {
			session.removeAttribute("user");
		}
		return "redirect:/index";
		
	}

	@RequestMapping("/login")
	public String showLogin(HttpServletRequest request) {
		//获取cookies
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				if ("uno".equals(cookie.getName())) {
					request.setAttribute(cookie.getName(), cookie.getValue());
				}
				if ("upwd".equals(cookie.getName())) {
					request.setAttribute(cookie.getName(), cookie.getValue());
				}
			}
		}

		return "login";
	}

	@RequestMapping("/reg")
	public String showReg() {
		return "reg";
	}

	@RequestMapping("register")
	@ResponseBody
	public Map<String, Object> register(User user) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (user.getUname() == null) {
			user.setUname(user.getUno());
		}
		user.setUpwd(EnDecryptUtil.SHA1(user.getUpwd()));
		user.setUimg("/images/default.gif");
		Boolean b = userService.addUser(user);
		if (b) {
			map.put("ret", 0);
			map.put("direct", "login");
		} else {
			map.put("ret", -1);
			map.put("msg", "抱歉，注册失败!");
		}

		return map;
	}

	/**
	 * 对用户名进行验证
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping("ValidateUsername")
	@ResponseBody
	public Integer validateUsername(@Param("username") String username) {
		// 判断用户名邮箱是否合法
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		boolean falg = false;

		Pattern pattern = Pattern.compile(str);
		falg = pattern.matcher(username).matches();
		// 用户名不合法
		if (!falg) {
			return -1;
		}
		Boolean b = userService.validateUno(username);
		// 判断用户名是否被占用，true为被占用
		if (b) {
			return -2;
		}
		return 1;
	}

	// 验证用户登录
	@RequestMapping("/checkLogin")
	public String checkLogin(User user, String rememberMe, HttpServletRequest request, HttpServletResponse response) {
		User checkUser = userService.checkUser(user.getUno(), user.getUpwd());
		if (checkUser != null) {
			if ("1".equals(rememberMe)) {
				Cookie uno = new Cookie("uno", checkUser.getUno());
				Cookie upwd = new Cookie("upwd", checkUser.getUpwd());
				uno.setMaxAge(3600 * 24 * 7);
				upwd.setMaxAge(3600 * 24 * 7);
				response.addCookie(uno);
				response.addCookie(upwd);
			} else {
				Cookie uno = new Cookie("uno", null);
				Cookie upwd = new Cookie("upwd", null);
				uno.setMaxAge(0);
				upwd.setMaxAge(0);
				response.addCookie(uno);
				response.addCookie(upwd);
			}
			// 讲用户添加进session中
			checkUser.setUpwd(null);
			request.getSession().setAttribute("user", checkUser);
			return "redirect:/index";
		} else {
			request.setAttribute("uno", user.getUno());
			request.setAttribute("errmsg", "您的用户名或密码不正确");
			return "login";
		}

	}

}
